const { DataTypes } = require("sequelize");
const sequelize = require("../db/connect");
const { Good, Sku } = require("./good");

const Order = sequelize.define("order", {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  // 订单编号
  orderNo: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  // 用户ID
  appUserId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  // 下单地址
  addressId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  // 订单总价
  totalPrice: {
    type: DataTypes.DECIMAL,
    allowNull: false,
  },
  // 订单状态 未支付 待发货 已发货 已完成 退款中 已退款 已取消
  status: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  // 快递编号
  delivery: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    updataValue: DataTypes.NOW,
  },
});

const OrderItem = sequelize.define("orderItem", {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  // 订单ID
  orderId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  // 商品ID
  goodId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  // SKU ID
  skuId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  // 数量
  quantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  // 单价
  price: {
    type: DataTypes.DECIMAL,
    allowNull: false,
  },
});

// 建立关联关系
Order.hasMany(OrderItem, { foreignKey: "orderId" });
OrderItem.belongsTo(Order, { foreignKey: "orderId" });

OrderItem.belongsTo(Good, { foreignKey: "goodId" });
OrderItem.belongsTo(Sku, { foreignKey: "skuId" });

module.exports = { Order, OrderItem };
